<template>
    <a-modal v-model:open="open" title="信息修改" @ok="handleOk" @cancel="handleCancel">
        <template #footer>
            <a-button key="back" @click="handleCancel">Return</a-button>
            <a-button key="submit" type="primary" :loading="loading" @click="handleOk">Submit</a-button>
        </template>
        <a-form :model="formState" name="EditSpots" v-bind="formItemLayout" @finishFailed="onFinishFailed"
            @finish="onFinish">
            <!-- 城市名称 -->
            <a-form-item name="cityname" label="所在城市" has-feedback
                :rules="[{ required: true, message: '景点所在城市不能为空!' }]">
                <a-select v-model:value="formState.cityname" :options="options.map(e => ({ value: e }))"
                    placeholder="请选择景点所在城市">
                </a-select>
            </a-form-item>
            <!-- 景点名称 -->
            <a-form-item name="name" label="景点名称" has-feedback :rules="[{ required: true, message: '景点名称不能为空!' }]">
                <a-input v-model:value="formState.name" placeholder="请输入景点名称" />
            </a-form-item>
            <!-- 景点地址 -->
            <a-form-item name="address" label="景点地址" has-feedback :rules="[{ required: true, message: '景点地址不能为空' }]">
                <a-input v-model:value="formState.address" placeholder="请输入景点地址" />
            </a-form-item>
            <!-- 景点电话 -->
            <a-form-item name="tel" label="景点电话" :rules="[{ required: false }]">
                <a-input v-model:value="formState.tel" placeholder="请输入景点电话" />
            </a-form-item>
            <!-- 景点坐标 -->
            <a-form-item name="postion" label="景点坐标" has-feedback :rules="[{ required: true, message: '景点坐标不能为空！' }]">
                <a-input v-model:value="formState.postion" placeholder="请输入景点坐标lng,lat" />
            </a-form-item>
            <!-- 景点评论 -->
            <a-form-item name="comment" label="景点评论" :rules="[{ required: false }]">
                <a-input v-model:value="formState.comment" placeholder="景点评论(选填)" />
            </a-form-item>
            <!-- 景点类型 -->
            <a-form-item name="type" label="景点类型" has-feedback :rules="[{ required: true, message: '景点类型不能为空!' }]">
                <a-select v-model:value="formState.type" mode="multiple" placeholder="请选择景点类型"
                    :options="typeOptions.map(e => ({ value: e }))">
                </a-select>
            </a-form-item>
            <!-- 景点评分 -->
            <a-form-item name="rate" label="景点评分" has-feedback :rules="[{ required: true, message: '景点评分不能为空!' }]">
                <a-rate v-model:value="formState.rate" allow-half />
            </a-form-item>
            <!-- 景点图片 -->
            <a-form-item name="photo" label="景点图片">
                <a-upload v-model:fileList="fileList" name="photo" :customRequest="customRequest"
                    list-type="picture-card" @preview="handlePreview" @change="photochange">
                    <div v-if="fileList.length < 3">
                        <plus-outlined />
                        <div style="margin-top: 8px">Upload</div>
                    </div>
                </a-upload>
                <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleformCancel">
                    <img alt="example" style="width: 100%" :src="previewImage" />
                </a-modal>
            </a-form-item>
        </a-form>
    </a-modal>
</template>
<script setup>
import { ref, watch, reactive } from 'vue';
import { spotsInfoStore } from '../../stores/spots';
import { editSpots } from '@/api/apitest';
import { message } from 'ant-design-vue';
import axios from 'axios';
const spotsStore = spotsInfoStore();


const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
const fileList = ref([]);
const handleformCancel = () => {
    previewVisible.value = false;
    previewTitle.value = '';
};

//form表单中上传图片部分
const customRequest = async ({ file, onSuccess, onProgress }) => {
    const formData = new FormData();
    formData.append('file', file);
    try {
        const res = await axios.post('http://localhost:3000/api/uploadFile', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            onUploadProgress: ({ loaded, total }) => {
                onProgress({ percent: (loaded / total) * 100 });
            }
        });

        // 关键：必须调用 onSuccess 并返回符合 a-upload 要求的格式
        onSuccess({
            uid: file.uid,
            name: file.name,
            status: 'done',
            url: res.data.path // 使用后端返回的完整 URL
        });


    } catch (error) {
        console.error('Upload failed:', error);
    }
};
//调整上传后返回图像数据存储格式
const photochange = (e) => {
    console.log(e.fileList, 'filelist', e.file.response, 'file');
    if (e.file.response) {
        for (let i = 0; i < e.fileList.length; i++) {
            const element = e.fileList[i];
            const temp = e.file.response
            if (element.uid === temp.uid) {
                e.fileList.splice(i, 1)
                e.fileList.push(temp)
                console.log(element, e.fileList);
            }
        }
    }

}
//预览照片
function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

const handlePreview = async file => {
    if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
    }
    previewImage.value = file.url || file.preview;
    previewVisible.value = true;
    previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};

//弹出对话框
const loading = ref(false);
const open = ref(false);
//提交表单
const handleOk = async () => {
    // console.log(formState, '表单数据', fileList.value, '图片');
    const location = formState.postion.split(',')
    const photos = []
    for (const e of fileList.value) {
        photos.push(e.url)
    }
    const data = [{
        id: formState.id,
        cityname: formState.cityname,
        name: formState.name,
        address: formState.address,
        rating: formState.rate,
        comment: formState.comment,
        tel: formState.tel,
        type: formState.type.join(';'),
        photos: photos,
        location: [Number(location[0]), Number(location[1])]
    }]
    // console.log(data);
    const res = await editSpots(data)
    // console.log(res, 'tessssst');
    spotsStore.SetSelectedSpot(res.data[0])//将修改后信息进行更新展示
    spotsStore.SetcityData(spotsStore.tempData.map(spot => spot.id === res.data[0].id ? res.data[0] : spot)); // 更新 cityData中修改数据
    spotsStore.SettempData(spotsStore.tempData.map(spot => spot.id === res.data[0].id ? res.data[0] : spot)); // 更新 tempData中修改数据
    loading.value = true;

    loading.value = false;
    spotsStore.SetEditOpen(false)
    message.success('修改景点信息成功！')
};
const handleCancel = () => {
    //关闭编辑对话框
    spotsStore.SetEditOpen(false)
};
//表单
const formItemLayout = {
    labelCol: {
        span: 6,
    },
    wrapperCol: {
        span: 14,
    },
};
const options = ['郑州市', '开封市', '洛阳市', '平顶山市', '安阳市', '鹤壁市', '新乡市', '焦作市', '濮阳市', '许昌市', '漯河市', '三门峡市', '南阳市', '商丘市', '信阳市', '周口市', '驻马店市', '济源市']
let typeOptions = ['风景名胜', '公园', '国家级景点', '博物馆', '休闲场所', '游乐园', '公园广场', '其他']
const formState = reactive({
    cityname: '',
    name: '',
    address: '',
    tel: '',
    postion: '',
    type: [],
    rate: 0,
    comment: '',
    id: 0,
});
const onFinish = values => {
    console.log('Success:', values);
    //关闭编辑对话框
    spotsStore.SetEditOpen(false)
};
const onFinishFailed = errorInfo => {
    console.log('Failed:', errorInfo);
    //关闭编辑对话框
    spotsStore.SetEditOpen(false)
};

// 监听 spotsStore.EditOpen 的变化
watch(() => spotsStore.EditOpen, (newVal) => {
    open.value = newVal;
});
//监听 spotsStore.EditOpen 的变化
// watch(() => fileList.value, (newVal) => {
//     fileList.value[2]
// });
// 监听 spotsStore.selectedSpot 的变化，并更新 formState
watch(() => spotsStore.selectedSpot, (newSpot) => {
    if (newSpot && newSpot.length > 0) {
        formState.cityname = JSON.parse(localStorage.getItem('cityData')) || '';
        formState.name = newSpot[0].spotname || '';
        formState.address = newSpot[0].address || '';
        formState.tel = newSpot[0].tel || '';
        formState.postion = newSpot[0].location ? newSpot[0].location.join(',') : '';
        formState.type = newSpot[0].type ? newSpot[0].type.split(';') : [];
        formState.rate = newSpot[0].rating || 0;
        formState.comment = newSpot[0].comment || '';
        formState.id = newSpot[0].id || '';
        // typeOptions = newSpot[0].type ? newSpot[0].type.split(';') : []
        fileList.value = [];
        for (let i = 0; i < newSpot[0].photos.length; i++) {
            fileList.value.push(
                {
                    uid: i + 1,
                    name: 'photo',
                    status: 'done',
                    url: newSpot[0].photos[i],
                },
            )

        }
    }
}, { deep: true });
</script>
<style lang="scss" scoped></style>